package com.tjk.crawler.service.red.service.imp;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.tjk.crawler.service.red.service.HuaweiService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author tangjiakai
 * @Date 2024/9/29 14:33
 */
@Service
public class HuaweiServiceImp implements HuaweiService {

    private final static Logger logger = LoggerFactory.getLogger(HuaweiServiceImp.class);


    @Override
    public void crawlerPhoneModels() {
        // 设置Chrome驱动路径
        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver\\chromedriver-win64\\chromedriver-win64\\chromedriver.exe");
        List<String> hrefList = new ArrayList<>();

        ChromeDriver chromeDriver = new ChromeDriver();

        chromeDriver.get("https://consumer.huawei.com/cn/support/product/");

        List<WebElement> titleList = chromeDriver.findElementById("smart-phone")
                .findElement(By.className("v3-prod-series-container-scrollbox"))
                .findElement(By.className("v3-container")).findElements(By.tagName("p"));
        //遍历每个标签页获取标签页下所有手机型号
        for (WebElement title : titleList) {
            title.click();
            //定位到手机型号详情div
            List<WebElement> phoneDetailDivList = chromeDriver.findElementById("smart-phone")
                    .findElement(By.className("v3-prod-list-container"))
                    .findElement(By.className("v3-row"))
                    .findElements(By.className("v3-prod-container"));
            for (WebElement phoneDetailDiv : phoneDetailDivList) {
                WebElement element = phoneDetailDiv.findElement(By.className("v3-prod-content"));
                String href = element.findElements(By.tagName("a")).get(0).getAttribute("href");
                hrefList.add(href);
            }
        }
        try {
            List<String> codeList = new ArrayList<>();
            //用来存储所有手机code
            for (int i = 0; i < hrefList.size(); i++) {
                String href = hrefList.get(i);
                //增加时间间隔防止爬取过快ip被封
//                Random random = new Random();
//                Thread.sleep(5000 + random.nextInt(1000) + 1);
                Thread.sleep(3000);
                chromeDriver.get(href);
                try {
                    //通过class获取到对应节点
                    WebElement webElement = chromeDriver.findElementByClassName("v3-select");
                    String fullName = webElement.getText();
                    //获取最后括号中的名称
                    int start = fullName.lastIndexOf("(");
                    //官网有bug 一些文字括号用的中文括号
                    if (start == -1) {
                        start = fullName.lastIndexOf("（");
                    }
                    int end = fullName.lastIndexOf(")");
                    if (end == -1) {
                        end = fullName.lastIndexOf("）");
                    }
                    String modelCode = fullName.substring(start + 1, end);
                    codeList.add(modelCode);
                    System.out.println("[" + i + "]" + modelCode + ";" + href);
                } catch (Exception e) {
                    System.out.println(i);
                    logger.error("[{}错误]{}", i, href);
                }

            }
            System.out.println(String.join(",", codeList));
            chromeDriver.quit();
        } catch (Exception e) {
            chromeDriver.quit();
            throw new RuntimeException(e);
        }
    }
}
